package com.yylending.las.main.message;

import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.network.NetworkHelper;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.network.entity.EmptyEntity;
import com.yylending.las.BuildConfig;
import com.yylending.las.Global;
import com.yylending.las.common.utils.TimeUtils;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
import rx.Observable;

import java.util.List;

/**
 * Created by HenryZhang on 2016/11/16.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class MessageModel extends Model {

	@Override
	public Observable getObservable(Object params, int functionalCode) {
		Service service = (Service) NetworkHelper.createService(Service.class);
		return service.getMsgList(Global.LOGIN_TOKEN, (EmptyEntity) params);
	}

	@Override
	public void onNext(Object entity) {
		MsgListResult msgList = cast(entity);
		//转换消息的时间戳为年.月.日的格式
		MessageModel.MsgResponse msgResponse = msgList.getData();
		List<Message> messages = msgResponse.rows;
		for (Message message : messages) {
			String messageTime = "";
			try {
				long millisTime = Long.parseLong(message.created);
				messageTime = TimeUtils.formatDateTimeDot(millisTime);
				message.created = messageTime;
			} catch (Exception e) {
				if (BuildConfig.DEBUG)
					e.printStackTrace();
			}
		}
		EventAgent.post(msgList);
	}

	private interface Service {
		@POST("server/message/getMessageList")
		Observable<MsgListResult> getMsgList(@Header("token") String token, @Body EmptyEntity params);
	}

	public static class RequestParams {
		public int pageNo;
		public int pageSize;

		public RequestParams(int pageNo, int pageSize) {
			this.pageNo = pageNo;
			this.pageSize = pageSize;
		}
	}

	static class MsgListResult extends BaseResultEntity<MsgResponse> {
	}

	static class MsgResponse {
		public int count;
		public List<Message> rows;
	}

	static class Message {
		/***
		 * ID
		 */
		public String mid;
		/***
		 * 发信人
		 */
		public String fromUserId;
		/***
		 * 收信人
		 */
		public String toUserId;
		/***
		 * 消息类型
		 */
		public String type;
		/***
		 * 消息标题
		 */
		public String title;
		/***
		 * 消息内容
		 */
		public String content;
		/***
		 * 消息创建时间
		 */
		public String created;
		/***
		 * 是否已读：0 未读 1 已读
		 */
		public String isRead;


	}
}
